package cn.bonoon.util;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import cn.bonoon.kernel.util.RSAUtil;

public class RSAManager {
	public final static RSAManager rsaManager = new RSAManager();
	
	private final String modulus;
	
	private final String exponent;
	
	private final RSAPublicKey rsaPublicKey;
	private final RSAPrivateKey rsaPrivateKey;
	
	private RSAManager(){
		String modulus, exponent;
		RSAPublicKey rsaPublicKey = null;
		RSAPrivateKey rsaPrivateKey = null;
		try {
			KeyPair keyPair = RSAUtil.genKeys(DateFormatUtils.format(new Date(), "yyyyMMdd"));
			rsaPublicKey = (RSAPublicKey)keyPair.getPublic();
			modulus = new String(Hex.encodeHex(rsaPublicKey.getModulus().toByteArray()));
			exponent = new String(Hex.encodeHex(rsaPublicKey.getPublicExponent().toByteArray()));
			
			rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate();
		} catch (Exception e) {
			e.printStackTrace();
			modulus = "";
			exponent = "";
		}
		this.modulus = modulus;
		this.exponent = exponent;
		
		this.rsaPublicKey = rsaPublicKey;
		this.rsaPrivateKey = rsaPrivateKey;
	}

	public String getExponent() {
		return exponent;
	}

	public String getModulus() {
		return modulus;
	}

	public RSAPublicKey getRsaPublicKey() {
		return rsaPublicKey;
	}

	public RSAPrivateKey getRsaPrivateKey() {
		return rsaPrivateKey;
	}
	
	public String decryptString(String encrypttext){
		try{
			byte[] en_data = Hex.decodeHex(encrypttext.toCharArray());
			byte[] data = RSAUtil.decrypt(en_data, rsaPrivateKey);
			return new String(data);
		}catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public String decryptJSString(String encrypttext){
		String data = decryptString(encrypttext);
		return StringUtils.reverse(data);
	}
}
